package angels.client.Activities;
import java.util.List;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import angels.client.R;
import angels.client.Entities.CustomItemizedOverlay;
import angels.client.Entities.CustomOverlayItem;
import angels.client.Entities.Sharing;
import angels.client.Entities.User;
import angels.client.Listeners.TrafficListener;
import angels.client.Listeners.UserListener;
import angels.client.Services.BusyHourService;
import angels.client.Services.UserService;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.GeoPoint;
import com.readystatesoftware.maps.OnSingleTapListener;
import com.readystatesoftware.maps.TapControlledMapView;
//for GPS test
import android.location.Criteria;
import android.location.LocationListener;
import android.location.LocationManager;

public class TrafficActivity extends MapActivity implements ServiceConnection, OnSharedPreferenceChangeListener, TrafficListener, UserListener {
	private BusyHourService service = null;
	private UserService userService = null;
	String selected_category;
	String selected_subcategory;
    private SharedPreferences prefs;	
    private TapControlledMapView mapView;
	private Sharing[] currentSharings;
	private Handler handler = new Handler(); 
	private CustomItemizedOverlay rAngels,gAngels,yAngels;
	private CustomItemizedOverlay gpsItemizedOverlay;
	private CustomItemizedOverlay selItemizedOverlay;
	GeoPoint gp = null;   
	GeoPoint selGP=null;
	LocationManager locMgr;
	MyLocationListener locLstnr;
	private boolean requestedMyLocation=true;
    
	
	
	public void onServiceConnected(ComponentName className, IBinder binder) {
		if (className.getClassName().equals(UserService.class.getName())){
			userService=((UserService.LocalBinder) binder).getService();
		}
		else{
			service = ((BusyHourService.LocalBinder) binder).getService();
			service.category=selected_category;
			service.subcategory=selected_subcategory;
			focusMyLocation();
			onTrafficSampled(service.getLatestTrafficUpdate()); // load current latest traffic update
			service.addTrafficListener(this); // register for future updates
			
			//Bitmap bitmap = ((BitmapDrawable)balloonDrawable).getBitmap();
			//balloonDrawable = new BitmapDrawable(Bitmap.createScaledBitmap(bitmap, 52, 52, true));
			
			Drawable locationDrawable = this.getResources().getDrawable(R.drawable.my_location);
			Drawable selLocationDrawable = this.getResources().getDrawable(R.drawable.status_bar_icon);
			
			gpsItemizedOverlay = new CustomItemizedOverlay(locationDrawable,mapView);
			
			selItemizedOverlay= new CustomItemizedOverlay(selLocationDrawable,mapView);
			
			rAngels = new CustomItemizedOverlay(this.getResources().getDrawable(R.drawable.angelred),mapView);
			yAngels = new CustomItemizedOverlay(this.getResources().getDrawable(R.drawable.angelyellow),mapView);
			gAngels = new CustomItemizedOverlay(this.getResources().getDrawable(R.drawable.angelgreen),mapView);
			
		}
	}

	public void onServiceDisconnected(ComponentName className) {
	    service = null;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.map);
			
		// initiate map

        mapView = (TapControlledMapView)findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        mapView.setSoundEffectsEnabled(true);
        mapView.getController().setZoom(2);
        
        prefs = PreferenceManager.getDefaultSharedPreferences(this);
        prefs.registerOnSharedPreferenceChangeListener(this);
        
        mapView.setSatellite(prefs.getBoolean("satelliteView", false));        
        
    	locMgr = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    	locLstnr = new MyLocationListener();
    	Criteria criteria = new Criteria();
    	criteria.setAccuracy(Criteria.ACCURACY_COARSE);  // Faster, no GPS fix.
    	criteria.setAccuracy(Criteria.ACCURACY_FINE);  // More accurate, GPS fix.
    	locMgr.requestLocationUpdates(locMgr.getBestProvider(criteria, true),
    	    0, 0, locLstnr);
        
        Bundle extras = getIntent().getExtras();
        selected_category = extras.getString("category");
        selected_subcategory = extras.getString("subcategory");
        
        // Bind service, for traffic updates
        Intent ServiceGps = new Intent(this, BusyHourService.class);
        getApplicationContext().bindService(ServiceGps, this, Context.BIND_AUTO_CREATE);
        
        Intent userservice = new Intent(this, UserService.class);
        getApplicationContext().bindService(userservice, this, Context.BIND_AUTO_CREATE);
        
        
        OnSingleTapListener lis = new OnSingleTapListener() {
			
			@Override
			public boolean onSingleTap(MotionEvent e) {
				selGP = mapView.getProjection().fromPixels(
		                    (int) e.getX(),
		                    (int) e.getY());

				List<Overlay> overlays = mapView.getOverlays();
				selItemizedOverlay.clear();
	  		   CustomOverlayItem overlayitem = new CustomOverlayItem(selGP,"","","",0,0,"",null);
	  		   selItemizedOverlay.addOverlay(overlayitem);
	  		   selItemizedOverlay.update();
	  		   mapView.postInvalidate();
	  		   overlays.add(selItemizedOverlay);
	  		   return true;
		}
		};
		
		mapView.setOnSingleTapListener(lis);
  	}
	
	protected void focusMyLocation(){ 
       // service.getMyLocation();
        Location myLocation=service.myLocation;
        if (myLocation!=null){
        	int longTemp = (int)(myLocation.getLongitude()* 1000000);
        	int latTemp = (int)(myLocation.getLatitude() * 1000000);
        	gp =  new GeoPoint(latTemp, longTemp);
        	mapView.getController().setZoom(16);
        	mapView.getController().animateTo(gp);
        	requestedMyLocation=false;
        }
        else gp=null;
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
	    if (service != null)
	        service.removeTrafficListener(this);
	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
	
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        // reload preferences
        mapView.setSatellite(prefs.getBoolean("satelliteView", false));
    }

    public void onTrafficSampled(Sharing[] robots) {
        if (rAngels == null && yAngels == null && gAngels == null)
            return; // leave previous update...
        currentSharings=robots;
        handler.post(new Runnable() {	
            public void run() {
        		drawSharings(currentSharings); 
            }
        });
    }
    
    
    public void drawSharings(Sharing[] sharings){
    	 List<Overlay> overlays = mapView.getOverlays();
    	 overlays.clear();
    	 if (service.myLocation!=null){
    	   gpsItemizedOverlay.clear();
  		   CustomOverlayItem overlayitem = new CustomOverlayItem(service.myLocation);
  		   gpsItemizedOverlay.addOverlay(overlayitem);
  		   gpsItemizedOverlay.update();
  		   mapView.postInvalidate();
  		   overlays.add(gpsItemizedOverlay);
  	   }
    	if (sharings!=null){
    	rAngels.clear();gAngels.clear();yAngels.clear();
    	for (Sharing sharing: currentSharings){
    		CustomOverlayItem overlayitem = new CustomOverlayItem(sharing.getCoords(), sharing.getName(),sharing.getDescription()
    				,sharing.getDuration(),sharing.getLikes(),sharing.getDislikes(),null,sharing);
    		if (sharing.getUserRating()<2.0)
    			rAngels.addOverlay(overlayitem);
    		else if (sharing.getUserRating()>=2.0  &&sharing.getUserRating()<3.0)
    			yAngels.addOverlay(overlayitem);
    		else if (sharing.getUserRating()>=3.0)
    			gAngels.addOverlay(overlayitem);
    	}
    	  rAngels.update();yAngels.update();gAngels.update(); 		
 		  
    	}
    	if (selGP!=null){
	    	CustomOverlayItem overlayitem = new CustomOverlayItem(selGP,"","","",0,0,"",null);
		   selItemizedOverlay.addOverlay(overlayitem);
		   selItemizedOverlay.update();
    	}
    	if (selGP!=null || sharings!=null)
			   mapView.postInvalidate();
    	if (selGP!=null)
		   overlays.add(selItemizedOverlay);
	   if (sharings!=null){
		   overlays.add(rAngels);overlays.add(yAngels);overlays.add(gAngels);}
    	 
    }
        
    @Override
  public boolean onCreateOptionsMenu(Menu menu)
  {
      MenuInflater inflater = getMenuInflater();
      inflater.inflate(R.layout.options_menu, menu);

      return true;
  }
      
      @Override
  public boolean onOptionsItemSelected(MenuItem item)
  {
      //when the menu button is clicked, a menu comes up
      switch (item.getItemId())
      {
      case R.id.streetViewItem:
    	  if (gp!=null){
    		  String streetViewUrl="google.streetview:cbll="+(((double)(selGP.getLatitudeE6())) / 1E6)+","+(((double)(selGP.getLongitudeE6())) / 1E6)+"&cbp=1,180,,0,1.0";
    	  	  Intent streetView = new Intent(android.content.Intent.ACTION_VIEW,Uri.parse(streetViewUrl));
    	  	  startActivity(streetView);
    	  }
    	  break;
              
      case R.id.settingsMenuItem:
              startActivity(new Intent(this, SettingsActivity.class));
              break;
              
      case R.id.shareMenuItem:
              final Dialog dialog = new Dialog(this);

              dialog.setContentView(R.layout.add_share);
              dialog.setTitle("Angels - Add a new Share");
              	
              TextView text = (TextView) dialog.findViewById(R.id.text);
              text.setText("Insert your content here:");
              final EditText desc=(EditText) dialog.findViewById(R.id.shareContent);
              //ImageView image = (ImageView) dialog.findViewById(R.id.image);
             // image.setImageResource(R.drawable.car);
              Button button = (Button) dialog.findViewById(R.id.btnShare);
              button.setBackgroundResource(R.drawable.custom_button_brown);
	          button.setOnClickListener(new OnClickListener() {
	              public void onClick(View v) {
	                  userService.setSharing(userService.getUsername(), desc.getText().toString(),selGP,
	                		  service.category,service.subcategory, TrafficActivity.this);
	                  dialog.hide();
	              }
	          });
              dialog.show();
              break;
      
      case R.id.centerOnLocationMenuItem:
    	  requestedMyLocation=true;
    	  focusMyLocation();
          break;
      }
      return true;
  }

	@Override
	public void onUserInfoReceived(User user) {}

	@Override
	public void onUserInfoSent() {}
	
	public class MyLocationListener implements LocationListener
	{

	@Override
	public void onLocationChanged(Location loc)
	{
	service.myLocation=loc;
	if (requestedMyLocation)
		focusMyLocation();
	}

	@Override
	public void onProviderDisabled(String provider)
	{
	Toast.makeText( getApplicationContext(),
	"Gps Disabled",
	Toast.LENGTH_SHORT ).show();
	// Start with fine location.
	Location loc = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
	if (loc == null) {
	  // Fall back to coarse location.
	  loc = locMgr.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
	}
	service.myLocation=loc;
	}

	@Override
	public void onProviderEnabled(String provider)
	{
	Toast.makeText( getApplicationContext(),
	"Gps Enabled",
	Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras)
	{

	}

	}	
}